import React, {useEffect, useState} from 'react';
import {
  Text,
  View,
  Image,
  TouchableWithoutFeedback,
  StyleSheet,
} from 'react-native';
import {useStyleConstants} from '../resources/StyleConstants';
import {useResponsive} from 'react-native-responsive-hook';
import ColorButton from '../components/ColorButton';
import Colors from '../resources/Colors';
import LoadingView from './LoadingView';
import {get} from '../http/http';
import Row from '../components/Row';

export default function ReserveView(props) {
  const {STYLES} = useStyleConstants();
  const {wp, hp, rem} = useResponsive();

  const [week, setWeek] = useState(0);
  const [data, setData] = useState(null);
  const [yuyueList, setYuyueList] = useState([]);

  const itemWidth = wp(4);
  const itemHeight = wp(4);

  const gray = '#bbcdc5';
  const keyue = '#a4e2c6';
  const blue = '#21a675';
  const red = '#e29c45';
  const greenOpen = '#bce672';
  const green = '#f9906f';

  const styles = StyleSheet.create({
    keyue: {
      width: itemWidth,
      height: itemHeight,
      backgroundColor: keyue,
    },
    color: {},
    gray: {
      width: itemWidth,
      height: itemHeight,
      backgroundColor: gray,
    },
    blue: {
      width: itemWidth,
      height: itemHeight,
      backgroundColor: blue,
    },
    red: {
      width: itemWidth,
      height: itemHeight,
      backgroundColor: red,
    },
    greenOpen: {
      width: itemWidth,
      height: itemHeight,
      backgroundColor: greenOpen,
    },
    green: {
      width: itemWidth,
      height: itemHeight,
      backgroundColor: green,
    },
  });

  const warehousingId = props.warehousingId;
  const modelId = props.modelId;

  useEffect(() => {
    const loadData = async () => {
      const {data} = await get(
        '/assets/assetsReserveOrder/api/getBackAssetsReserveByWeek',
        {
          week,
          warehousingId,
        },
      );
      setData(data);
    };
    const loadData2 = async () => {
      const {data} = await get(
        '/assets/equipmentApi/api/getAssetsModelReserveByWeekApi',
        {
          week,
          modelId,
        },
      );
      setData(data);
    };
    if (warehousingId) {
      loadData();
    }
    if (modelId) {
      loadData2();
    }
  }, [warehousingId, modelId, week]);
  const isYuYue = (startTime, endTime, date) => {
    const item = `${date} ${startTime}-${endTime}`;
    return yuyueList.indexOf(item) >= 0;
  };
  const yuyue = (startTime, endTime, date) => {
    const item = `${date} ${startTime}-${endTime}`;
    if (yuyueList.indexOf(item) >= 0) {
      // 删除
      const newYuyueList = yuyueList.filter(i => i !== item);
      setYuyueList(newYuyueList);
      props.onReserveChange && props.onReserveChange(newYuyueList);
    } else {
      // 添加
      const newYuyueList = [...yuyueList, item];
      setYuyueList(newYuyueList);
      props.onReserveChange && props.onReserveChange(newYuyueList);
    }
  };

  const renderCell = (d, item, index) => {
    let backgroundColor = gray;
    let disabled = false;
    if (
      new Date().getTime() > new Date(item.date + ' ' + d.startTime).getTime()
    ) {
      backgroundColor = gray;
      disabled = true;
    } else {
      if (d.isOpen === 1) {
        backgroundColor = greenOpen;
      } else {
        const day = [
          d.monday,
          d.tuesday,
          d.wednesday,
          d.thursday,
          d.friday,
          d.saturday,
          d.sunday,
        ][index];
        if (day.isHas && !isYuYue(d.startTime, d.endTime, item.date)) {
          disabled = true;
          if (day.orderType === 0) {
            backgroundColor = blue;
          } else if (day.orderType === 1) {
            backgroundColor = red;
          } else {
            backgroundColor = green;
          }
        } else {
          if (isYuYue(d.startTime, d.endTime, item.date)) {
            backgroundColor = '#00e079';
            console.log('--------->');
          } else {
            backgroundColor = keyue;
          }
        }
      }
    }

    return (
      <TouchableWithoutFeedback
        disabled={disabled}
        onPress={() => yuyue && yuyue(d.startTime, d.endTime, item.date)}>
        <View
          style={{
            backgroundColor: backgroundColor,
            width: '95%',
            flex: 1,
            margin: '2.5%',
            maxHeight: hp(15),
          }}>
          <Text
            style={{
              textAlign: 'center',
              color: 'white',
              fontSize: rem(6),
              textAlignVertical: 'center',
              lineHeight: hp(3),
            }}>
            {
              [
                d.monday,
                d.tuesday,
                d.wednesday,
                d.thursday,
                d.friday,
                d.saturday,
                d.sunday,
              ][index].teacherName
            }
          </Text>
        </View>
      </TouchableWithoutFeedback>
    );
  };
  const handlePrevWeek = () => setWeek(prev => prev - 1);
  const handleNextWeek = () => setWeek(prev => prev + 1);
  if (!data) {
    return <LoadingView />;
  }

  return (
    <View
      style={{
        width: '100%',
        alignItems: 'stretch',
        flex: 1,
        borderRadius: 20,
        paddingHorizontal: '1%',
        paddingBottom: '3%',
        paddingTop: '2%',
      }}>
      <View style={{width: '100%', height: '100%', alignItems: 'center'}}>
        <View
          style={{
            flexDirection: 'row',
            width: '100%',
            justifyContent: 'space-around',
            alignItems: 'center',
            position: 'absolute',
            left: 0,
            top: -hp(2),
            right: 0,
            zIndex: 100,
          }}>
          <ColorButton
            title="上一周"
            backgroundColor={Colors.primaryColor}
            fontSize={rem(6)}
            height={hp(3)}
            containerStyle={{paddingHorizontal: wp(4)}}
            onPress={handlePrevWeek}
          />
          <Text
            style={{
              color: '#333',
              marginHorizontal: wp(2),
              fontSize: rem(8),
              fontWeight: 'bold',
            }}>
            {data.currentDay}
          </Text>
          <ColorButton
            title="下一周"
            backgroundColor={Colors.primaryColor}
            fontSize={rem(6)}
            height={hp(3)}
            containerStyle={{paddingHorizontal: wp(4)}}
            onPress={handleNextWeek}
          />
        </View>
        <View
          style={{
            flexDirection: 'row',
            borderRadius: 20,
            padding: '1%',
            marginTop: hp(1),
            flex: 1,
          }}>
          <View style={{flex: 1}}>
            <View
              style={{
                backgroundColor: '#71C6CB',
                borderBottomColor: '#005156',
                borderBottomWidth: 0.5,
                height: hp(5),
                justifyContent: 'center',
              }}>
              <Text
                style={{textAlign: 'center', color: 'white', fontSize: rem(8)}}>
                时间
              </Text>
            </View>
            {data.tableData &&
              data.tableData.map((item, index) => {
                return (
                  <View
                    key={index}
                    style={{
                      height: hp(5),
                      backgroundColor:
                        index < 4
                          ? '#FAEDE4'
                          : index < 9
                          ? '#F6FAE4'
                          : '#E4FAEC',
                      flex: 1,
                      maxHeight: hp(15),
                      textAlign: 'center',
                      borderBottomColor: '#005156',
                      borderBottomWidth: 1,
                      borderRightWidth: 1,
                      borderRightColor: '#005156',
                      justifyContent: 'center',
                    }}>
                    <Text style={{textAlign: 'center', fontSize: rem(8)}}>
                      {item.startTime}-{item.endTime}
                    </Text>
                  </View>
                );
              })}
          </View>

          {data.weekList &&
            data.weekList.map((item, index) => {
              return (
                <View key={index} style={{flex: 1}}>
                  <View
                    style={{backgroundColor: '#71C6CB', textAlign: 'center'}}>
                    <Text
                      style={{
                        textAlign: 'center',
                        color: 'white',
                        lineHeight: hp(5),
                        height: hp(5),
                        fontSize: rem(8),
                      }}>
                      {item.week}
                      {item.time}
                    </Text>
                  </View>
                  {data.tableData &&
                    data.tableData.map((d, i) => {
                      return (
                        <View
                          key={i + index * 20}
                          style={{
                            flexDirection: 'column',
                            backgroundColor: 'white',
                            flex: 1,
                            maxHeight: hp(15),
                            textAlign: 'center',
                            borderBottomColor: '#005156',
                            borderBottomWidth: 1,
                            borderRightWidth: 1,
                            borderRightColor: '#005156',
                          }}>
                          {renderCell(d, item, index)}
                        </View>
                      );
                    })}
                </View>
              );
            })}
        </View>
        <View
          style={{
            flexDirection: 'row',
            alignItems: 'center',
            width: '60%',
            justifyContent: 'space-around',
            alignSelf: 'flex-start',
          }}>
          <View>
            <Text>颜色说明</Text>
          </View>
          <Row>
            <View style={styles.keyue} />
            <Text style={{fontSize: rem(7), marginLeft: 5}}>可约时段</Text>
          </Row>
          <Row>
            <View style={styles.gray} />
            <Text style={{fontSize: rem(7), marginLeft: 5}}>过期时段</Text>
          </Row>
          <Row>
            <View style={styles.blue} />
            <Text style={{fontSize: rem(7), marginLeft: 5}}>正常预约</Text>
          </Row>
          <Row>
            <View style={styles.green} />
            <Text style={{fontSize: rem(7), marginLeft: 5}}>占用</Text>
          </Row>
        </View>
      </View>
    </View>
  );
}
